# coding:utf-8
import glob
import os
import random
import pandas as pd
import xml.etree.ElementTree as ET
csv_dir=r"/home/hiicy/redldw/ldwred/box_csv"
def xml_to_csv(path):
    xml_files=[]
    for xml_file in glob.glob(path + '/*.xml'):
        xml_files.append(xml_file)
    random.shuffle(xml_files)
    leth = len(xml_files)
    trate = int(leth*0.8)
    def godo(xml_files,type='train'):
        xml_list = []
        for xml_file in xml_files:
            prefix = os.path.split(xml_file)[0]
            tree = ET.parse(xml_file)
            root = tree.getroot()
            # print(root)
            print(root.find('filename').text)
            for member in root.findall('object'):
                value = (root.find('filename').text,
                        int(root.find('size')[0].text),   #width
                        int(root.find('size')[1].text),   #height
                        member[0].text,
                        int(member[4][0].text),
                        int(float(member[4][1].text)),
                        int(member[4][2].text),
                        int(member[4][3].text)
                        )
                xml_list.append(value)
        column_name = ['filename', 'width', 'height', 'class', 'xmin', 'ymin', 'xmax', 'ymax']
        xml_df = pd.DataFrame(xml_list, columns=column_name)
        xml_df.to_csv(f'{csv_dir}/{type}_.csv', index=None)
    godo(xml_files[:trate])
    godo(xml_files[trate:],type='valid')

# path = r'E:\src\keras-yolo3-master\VOCdevkit\VOC2007\Annotations'
path = r'/home/hiicy/redldw/ldw/models-master/research/voc/VOCdevkit/VOC2007/Annotations'
xml_to_csv(path)